<?php
/**
 * vanephp web framework
 * 分页助手
 *
 * @author aray <ofree@qq.com>
 * @link http://www.vanephp.com/s
 * @copyright Copyright &copy; 2010 aray
 * @license http://www.vanephp.com/license
 * @package helper
 */

if ( ! defined ( 'INVANE' ) )
	exit ( '!' );

class vane_helper_pager {
	public function paging ( $tableObj, $fields, $conditions, $order = null, $page = 1, $pagesize = 10 ) {
		$page = $page < 1 ? $page = 1 : $page;
		$pagesize = $pagesize < 1 ? 1 : $pagesize;
		
		$start = ($page - 1) * $pagesize;
		$rows = $tableObj->findAll ( $fields, $conditions, $order, $start, $pagesize );
		$count = $tableObj->findCount ( $conditions );
		
		return $this->cumpPaging ( $rows, $count, $page, $pagesize );
	}
	
	public function cumpPaging ( $rows, $count, $page, $pagesize ) {
		$info = array (
			'rows' => $rows 
		);
		// 总记录
		$info['count'] = $count;
		// 分页大小
		$info['pagesize'] = $pagesize;
		// 总页数
		$info['pages'] = ceil ( $info['count'] / $pagesize );
		$info['pages'] = $info['pages'] <= 0 ? 1 : $info['pages'];
		// 首页
		$info['first'] = 1;
		// 上一页
		$info['prev'] = $page == 1 ? '' : $page - 1;
		// 当前页
		$info['current'] = $page;
		// 下一页
		$info['next'] = $page == $info['pages'] ? '' : $page + 1;
		// 尾页
		$info['last'] = $info['pages'] > 0 ? $info['pages'] : 1;
		// 过度页码
		$info['cross'] = array ();
		if ( $info['pages'] < 5 ) {
			for ( $i = 1 ; $i <= $info['pages'] ; $i ++ ) {
				$info['cross'][] = $i;
			}
		} else {
			if ( $page > 3 ) {
				for ( $i = 1 ; $i <= 3 ; $i ++ ) {
					$info['cross'][] = $i;
				}
				$info['cross'][] = '...';
				if ( $page + 3 < $info['pages'] ) {
					for ( $i = $page ; $i <= $page + 3 ; $i ++ ) {
						$info['cross'][] = $i;
					}
					$info['cross'][] = '...';
					for ( $i = $info['pages'] - 3 ; $i < $info['pages'] ; $i ++ ) {
						$info['cross'][] = $i;
					}
				} else {
					for ( $i = $info['pages'] - 3 ; $i <= $info['pages'] ; $i ++ ) {
						$info['cross'][] = $i;
					}
				}
			} else {
				for ( $i = 1 ; $i <= 3 ; $i ++ ) {
					$info['cross'][] = $i;
				}
				$info['cross'][] = '...';
				for ( $i = $info['pages'] - 3 ; $i < $info['pages'] ; $i ++ ) {
					$info['cross'][] = $i;
				}
			}
		}
		return $info;
	}
} 